package org.atovio.quickweb.controller;

import org.atovio.quickweb.vo.Article;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AtoVio, Winter Yuan
 */
@RestController
public class ArticleController {

    /**
     * 增加文章
     * 注解@Validated 验证Bean， 就是开启验证的意思
     * @param article 实例
     * @param br 收集的错误信息
     * @return 不知道
     */
    @PostMapping("/articles")
    public Map<String, Object> addArticle(@Validated(Article.AddArticleGroup.class) @RequestBody Article article,
                                          BindingResult br) {
        // 调用service方法

        // 返回数据结果
        return getErrorsMap(br);
    }
    
    @PutMapping("/articles")
    public Map<String, Object> editArticle(@Validated(Article.EditArticleGroup.class) @RequestBody Article article,
                                          BindingResult br) {
        // 调用service方法

        // 返回数据结果
        return getErrorsMap(br);
    }

    private static Map<String, Object> getErrorsMap(BindingResult br) {
        Map<String, Object> map = new HashMap<>();
        if (br.hasErrors()) {
            List<FieldError> fieldErrors = br.getFieldErrors();

            for (int i = 0, len = fieldErrors.size(); i < len; i ++) {
                FieldError error = fieldErrors.get(i);
                map.put(i + "-" + error.getField(), error.getDefaultMessage());
            }
        }
        return map;
    }
}
